package com.szosen.device.Glucose;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.sinocare.Impl.SC_BlueToothCallBack;
import com.sinocare.Impl.SC_BlueToothSearchCallBack;
import com.sinocare.Impl.SC_CurrentDataCallBack;
import com.sinocare.domain.BloodSugarData;
import com.sinocare.domain.BlueToothInfo;
import com.sinocare.handler.SN_MainHandler;
import com.sinocare.protocols.ProtocolVersion;
import com.sinocare.status.SC_DataStatusUpdate;
import com.sinocare.status.SC_ErrorStatus;
import com.szosen.application.MyApplication;
import com.szosen.bluetooth.BluetoothListActivity;
import com.szosen.database.DBService;
import com.szosen.database.xuetang;
import com.szosen.jkzj.R;
import com.szosen.jkzj.activity.BaseActivity;
import com.szosen.jkzj.util.Contants;
import com.szosen.util.Cache;
import com.szosen.util.TimeHelper;
import com.szosen.util.ToastTool;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 血糖测量
 */
public class GLUSanNuo_Activity extends BaseActivity {
    private Cache cache;
    private String mDeviceName;
    private String mDeviceAddress;
    /*
     * private TextView tvaddress; private TextView tvstate;
     */
    private boolean result;
    private int tyear = 0;
    private int tmon = 0;
    private int tday = 0;
    private int thour = 0;
    private int tmin = 0;
    private int tsec = 0;
    private int xuhao = 0;
    public static Context myContext;

    private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
    EditText gluse_value_et;// 血糖值
    EditText xt_data;// 时间
    TextView connect_status;// 连接状态
    ImageView glu_image;// 上传状态
    Button upload_button;
    String from = "";
    private BluetoothAdapter mBluetoothAdapter;
    private String yibangding = "已绑定";
    String mMeasureTime = "";
    private SN_MainHandler sn_MainHandler = null;
    // 从哪里来的标记
    public static final String FLAG_FROM = "xuetangflag";
    public static final String FLAG_FROM_TYPE = "xuetangflag_type";
    public static final String FLAG_FROM_TYPE_BEFORE = "xuetangflag_type_before";
    public static final String FLAG_FROM_TYPE_AFTER = "xuetangflag_type_after";

    // 代码管理服务生命周期。
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_measure_glucose);
        super.setTitleContent("【三诺血糖测量】");
        context = this;
        cache = new Cache(this);
        InitView();
        checkBTOK();
        String address = MyApplication.getCache().getDeviceAddress(
                Cache.GLU_SANNUO);
        if (!TextUtils.isEmpty(address)) {
            // 直连蓝牙设备。
            connect_status
                    .setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTING);
            connect_status.setTextColor(Color.BLUE);
            connectBT(address);
        } else {
            connect_status
                    .setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECT_NOBOND);
            connect_status.setTextColor(Color.BLUE);
            // scanLeDevice(true);
        }
        needConnectBT = true;
    }

    public void connectDeviceAgain(View view) {
        String address = MyApplication.getCache().getDeviceAddress(
                Cache.GLU_SANNUO);
        if (!TextUtils.isEmpty(address)) {
            connectBT(address);
        } else {
            ToastTool.showShort(context, "未找到已绑定设备！");
            scanLeDevice(true);
        }
    }

    private boolean needConnectBT = false;

    // 检查bt是否ok
    private void checkBTOK() {
        registerReceiver(mBtReceiver, makeIntentFilter());
        initBT();// 初始化蓝牙
        if (sn_MainHandler != null && sn_MainHandler.isConnecting()) {
            Toast.makeText(context, "正在断开，请稍等", Toast.LENGTH_SHORT).show();
            return;
        }
        scanLeDevice(true);// 开始扫描设备。
    }

    private Map<String, SiriListItem> devices = new HashMap<String, SiriListItem>();
    private ArrayList<SiriListItem> list = new ArrayList<SiriListItem>();
    boolean isbtconn = false;
    TimerTask task = null;
    Timer timer = null;

    // 蓝牙连接，断开连接之后重新连接
    private void connectBT(final String address) {
        if (timer != null) {
            timer.cancel();
        }
        if (task != null) {
            task.cancel();
        }
        // 每次连接后都设计一个定时器。
        task = new TimerTask() {
            @Override
            public void run() {
                try {
                    String connectStatus = connect_status.getText().toString();
                    System.out.println("执行了10秒的计时器");
                    if (connectStatus
                            .equals(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTING)) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                connect_status
                                        .setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTFAILED);
                                connect_status.setTextColor(Color.RED);
                            }
                        });

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        timer = new Timer();
        timer.schedule(task, 10000L);
        MyApplication.getCache().saveDeviceAddress(Cache.GLU_SANNUO, address);
        BluetoothDevice device = BluetoothAdapter.getDefaultAdapter()
                .getRemoteDevice(address);
        // 调用sdk连接蓝牙
        sn_MainHandler.connectBlueTooth(device, new SC_BlueToothCallBack() {
            @Override
            public void onConnectFeedBack(int result) {
                System.out.println("蓝牙连接onConnectFeedBack状态" + result);
            }
        });
        sn_MainHandler
                .registerReceiveBloodSugarData(new SC_CurrentDataCallBack<BloodSugarData>() {

                    @Override
                    public void onStatusChange(int status) {
                        if (status == SC_DataStatusUpdate.SC_BLOOD_FFLASH) {
                            // ToastTool.showShort(GLUSanNuo_Activity.this,
                            // "请插入试条测试！");
                        } else if (status == SC_DataStatusUpdate.SC_MC_TESTING) {
                            ToastTool.showShort(GLUSanNuo_Activity.this,
                                    "正在测试，请稍后！");
                        } else if (status == SC_DataStatusUpdate.SC_MC_SHUTTINGDOWN) {
                            ToastTool.showShort(GLUSanNuo_Activity.this,
                                    "正在关机！");
                        } else if (status == SC_DataStatusUpdate.SC_MC_SHUTDOWN) {
                            ToastTool
                                    .showShort(GLUSanNuo_Activity.this, "已关机！");
                            connect_status
                                    .setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTFAILED);
                            connect_status.setTextColor(Color.RED);
                        }
                    }

                    @Override
                    public void onReceiveSyncData(BloodSugarData datas) {

                    }

                    @Override
                    public void onReceiveSucess(BloodSugarData datas) {
                        float v = datas.getBloodSugarValue();
                        Date date = datas.getCreatTime();
                        float t = datas.getTemperature();
                        gluse_value_et.setText(v + "");
                        // ToastTool.showShort(context, "测试结果：" + v + "mmol/l,"
                        // + "时间：" + date.toLocaleString() + "当前温度：" + t
                        // + "°");
                        System.out.println("测试结果：" + v + "mmol/l," + "时间："
                                + date.toLocaleString() + "当前温度：" + t + "°");
                        xt_data.setText(TimeHelper.getTimeByDate(date));
                    }
                });
    }

    boolean mScanning;
    int destoryFlag = 0;
    BluetoothDevice mDevice = null;
    Runnable mRunnable = null;

    private void initBT() {
        // 初始化蓝牙设备，并搜索蓝牙信号。
        sn_MainHandler = SN_MainHandler.getBlueToothInstance();
        sn_MainHandler.initSDK(context, ProtocolVersion.WL_1);// 双模 手机支持BLE 使用BLE方式
//		SN_MainHandler.setBleSupported(true);// ble模式
    }

    private void scanLeDevice(final boolean enable) {
        sn_MainHandler
                .searchBlueToothDevice(new SC_BlueToothSearchCallBack<BlueToothInfo>() {
                    @Override
                    public void onBlueToothSeaching(BlueToothInfo newDevice) {
                        SiriListItem sir = new SiriListItem(newDevice.getName()
                                + "\n" + newDevice.getDevice().getAddress(),
                                false, newDevice);
                        BluetoothDevice device = newDevice.getDevice();
                        System.out.println("获取设备mac地址" + device.getAddress());
                        devices.put(newDevice.getDevice().getAddress(), sir);
                        // 扫描增加Sinocard三诺的血糖设备
                        if (device.getName() != null
                                && device.getName().contains("inocare")) {
                            String defaultAddress = MyApplication.getCache()
                                    .getDeviceAddress(Cache.GLU_SANNUO);
                            if (!TextUtils.isEmpty(defaultAddress)
                                    && defaultAddress.equals(device
                                    .getAddress())) {
                                addData(device.getName() + "(" + yibangding
                                        + ")", device.getAddress());
                                System.out.println("已绑定名字" + device.getName());
                                mDevice = device;
                                mDeviceAddress = device.getAddress();
                                System.out
                                        .println("获取设备mac地址" + mDeviceAddress);
                            } else {
                                addData(device.getName(), device.getAddress());
                            }
                            // 如果第一次使用，没绑定过设备。
                            if (TextUtils.isEmpty(defaultAddress)) {
                                // 这里需要增加一个蓝牙的列表。然后点击后就得到这个设备，然后连接。
                            }
                        }
//						addData(newDevice.getName(), newDevice.getDevice()
//								.getAddress());
                    }
                });
    }

    // 扫描装置的回调。
    private MyAdapter mMyAdapter;
    ArrayList<String[]> deviceMacList = new ArrayList<String[]>();

    public class SiriListItem {
        String message;
        boolean isSiri;
        BlueToothInfo info;

        public SiriListItem(String msg, boolean siri, BlueToothInfo infos) {
            message = msg;
            isSiri = siri;
            info = infos;
        }
    }

    // 增加到蓝牙列表
    private void addData(String name, String mac) {
        System.out.println("增加了绑定列表的设备" + name + mac);
        boolean isHas = false;
        for (int i = 0; i < deviceMacList.size(); i++) {
            String[] item = deviceMacList.get(i);
            String m = item[1];
            if (m.equals(mac)) {
                isHas = true;
            }
        }
        if (!isHas) {
            deviceMacList.add(new String[]{name, mac});
        }
        // 通知更新listView
        if (mMyAdapter != null) {
            mMyAdapter.notifyDataSetChanged();
        }
    }

    String this_bt_name = "", this_bt_mac = "";

    private void showDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(
                GLUSanNuo_Activity.this);
        LayoutInflater inflater = (LayoutInflater) GLUSanNuo_Activity.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout tl = (LinearLayout) inflater.inflate(
                R.layout.activity_tiwen_dialog_chancedevice, null);
        final ListView lv_btdevice_lists = (ListView) tl
                .findViewById(R.id.lv_btdevice_lists);
        final LinearLayout ll_password = (LinearLayout) tl
                .findViewById(R.id.ll_tiwen_password);
        final EditText et_password = (EditText) ll_password
                .findViewById(R.id.et_tiwen_password);
        mMyAdapter = new MyAdapter(deviceMacList);
        lv_btdevice_lists.setAdapter(mMyAdapter);

        lv_btdevice_lists.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // 点击一个蓝牙设备，就设定连接这个设备
                // 设置显示修改设备
                // 先把已经连接的取消。再连接新的。
                String[] item = (String[]) parent.getAdapter()
                        .getItem(position);
                System.out.println("蓝牙名称：" + item[0] + ",蓝牙mac地址：" + item[1]);
                this_bt_name = item[0];
                this_bt_mac = item[1];
                if (!item[0].contains(yibangding)) {
                    ll_password.setVisibility(View.VISIBLE);
                } else {
                    connectBT(this_bt_mac);
                    builder.create().dismiss();
                }
                // scanLeDevice(false);
            }
        });
        builder.setView(tl);
        builder.setTitle("请选择蓝牙设备：");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (ll_password.getVisibility() != View.VISIBLE) {
                    return;
                }
                String password = et_password.getText().toString();
                if (!TextUtils.isEmpty(password)
                        && BluetoothListActivity.changeDevicePassword
                        .equals(password)) {
                    // 把蓝牙设备列表清除。重新找设备。
                    clearAllList();
                    connectBT(this_bt_mac);
                    dialog.dismiss();
                } else {
                    ToastTool.showShort(context, "密码不正确！");
                }
                // scanLeDevice(false);
            }
        });
        builder.setNegativeButton("取消", null);
        mDeviceDialog = builder.create();
        mDeviceDialog.show();
    }

    private AlertDialog mDeviceDialog = null;

    private void clearAllList() {
        if (deviceMacList != null) {
            deviceMacList.clear();
        }
    }

    class MyAdapter extends BaseAdapter {
        private ArrayList<String[]> mList = new ArrayList<String[]>();

        MyAdapter(ArrayList<String[]> list) {
            mList = list;
        }

        public void addData(String name, String mac) {
            boolean isHas = false;
            for (int i = 0; i < mList.size(); i++) {
                String[] item = mList.get(i);
                String m = item[1];
                if (m.equals(mac)) {
                    isHas = true;
                }
            }
            if (!isHas) {
                mList.add(new String[]{name, mac});
            }
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public String[] getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressLint("InflateParams")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder holder;
            // 只有为空时才构造
            if (convertView == null) {
                holder = new Holder();
                LayoutInflater inflater = LayoutInflater.from(context);
                convertView = inflater.inflate(
                        R.layout.tiwen_listview_item_layout, null);
                holder.tv_name = (TextView) convertView
                        .findViewById(R.id.tiwen_listview_item_tv_name);
                holder.tv_mac = (TextView) convertView
                        .findViewById(R.id.tiwen_listview_item_tv_mac);
                convertView.setTag(holder);
            } else {
                holder = (Holder) convertView.getTag();
            }
            String[] s = mList.get(position);
            holder.tv_name.setText(s[0]);
            holder.tv_mac.setText(s[1]);
            return convertView;
        }

        class Holder {
            TextView tv_name;// 蓝牙名字
            TextView tv_mac;// mac地址
        }

    }

    /**
     * 销毁广播接收器
     */
    @Override
    protected void onPause() {
        super.onPause();
        try {
            // unregisterReceiver(mGattUpdateReceiver);
        } catch (Exception e) {
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onBackPressed() {
        // 作为SDK时销毁Activity不关闭Handler，保持蓝牙通信不断开
        // 导航软件请在主进程退出时调用close()方法关闭蓝牙通信模块
        /*
         * try { sn_MainHandler.disconnectDevice(); sn_MainHandler.close();
		 * unregisterReceiver(mBtReceiver); System.out.println("已经销毁了广播了。"); }
		 * catch (Exception e) { e.printStackTrace(); Log.e("onDestroy",
		 * "广播没有注册"); }
		 */
        String connectStatus = connect_status.getText().toString();
        if (connectStatus
                .equals(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTING)) {
            ToastTool.showLong(context, "正在连接设备，请勿退出!");
        } else {
            super.onBackPressed();
        }
    }

    // 广播监听SDK ACTION
    private final BroadcastReceiver mBtReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (SN_MainHandler.ACTION_SN_CONNECTION_STATE_CHANGED
                    .equals(action)) {
                if (sn_MainHandler.isConnected()) {
                    System.out.println("设备已经连接。。。。");
                    connect_status
                            .setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTSUCCESS);
                    connect_status.setTextColor(Color.BLUE);
                } else if (sn_MainHandler.isIdleState()) {
                    System.out.println("连接为空闲状态。。。。");
                    // connect_status
                    // .setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTFAILED);
                    // connect_status.setTextColor(Color.RED);
                } else if (sn_MainHandler.isDisconnecting()) {
                    System.out.println("已经断开连接。。。。");
                    connect_status
                            .setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTFAILED);
                    connect_status.setTextColor(Color.RED);
                } else if (sn_MainHandler.isSearching()) {
                }
            } else if (SN_MainHandler.ACTION_SN_ERROR_STATE.equals(action)) {
                Bundle bundle = intent.getExtras();
                int errorStatus = bundle
                        .getInt(SN_MainHandler.EXTRA_ERROR_STATUS);
                if (errorStatus == SC_ErrorStatus.SC_OVER_RANGED_TEMPERATURE)
                    ToastTool.showShort(context, "错误：超过仪器测试温度范围！");
                else if (errorStatus == SC_ErrorStatus.SC_AUTH_ERROR)
                    ToastTool.showShort(context, "错误：认证失败！");
                else if (errorStatus == SC_ErrorStatus.SC_ERROR_OPERATE)
                    ToastTool.showShort(context, "错误操作！！");
                else if (errorStatus == SC_ErrorStatus.SC_ABLOVE_MAX_VALUE)
                    ToastTool.showShort(context, "错误：测试结果大于33.3mmol/L！");
                else if (errorStatus == SC_ErrorStatus.SC_BELOW_LEAST_VALUE)
                    ToastTool.showShort(context, "错误：测试结果小于1.1mmol/L！");
                else if (errorStatus == SC_ErrorStatus.SC_LOW_POWER)
                    ToastTool.showShort(context, "错误：电力不足！");
                else if (errorStatus == SC_ErrorStatus.SC_UNDEFINED_ERROR)
                    ToastTool.showShort(context, "未知错误！");
                else if (errorStatus == 6)
                    ToastTool.showShort(context, "E-6");
            } else if (SN_MainHandler.ACTION_SN_MC_STATE.equals(action)) {
                Bundle bundle = intent.getExtras();
                int MCStatus = bundle.getInt(SN_MainHandler.EXTRA_MC_STATUS);
            }

        }
    };

    private IntentFilter makeIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter
                .addAction(SN_MainHandler.ACTION_SN_CONNECTION_STATE_CHANGED);
        intentFilter.addAction(SN_MainHandler.ACTION_SN_ERROR_STATE);
        intentFilter.addAction(SN_MainHandler.ACTION_SN_MC_STATE);
        return intentFilter;
    }

    /**
     * 结束服务
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 作为SDK时销毁Activity不关闭Handler，保持蓝牙通信不断开
        // 导航软件请在主进程退出时调用close()方法关闭蓝牙通信模块
        try {
            // 断开设备连接
            if (sn_MainHandler != null) {
                sn_MainHandler.close();
            }
            unregisterReceiver(mBtReceiver);
            System.out.println("已经销毁了广播了。");
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("onDestroy", "广播没有注册");
        }
    }

    RadioButton btn_after, btn_before;

    /**
     * 初始化控件
     */
    private void InitView() {
        from = getIntent().getStringExtra("xuetangflag");
        Button connect_device = (Button) findViewById(R.id.connect_device);
        connect_device.setVisibility(View.INVISIBLE);
        gluse_value_et = (EditText) findViewById(R.id.gluse_value_et);
        String time = TimeHelper.getCurrentTime();
//        gluse_value_et.setText(time);
        xt_data = (EditText) findViewById(R.id.xt_data);
        xt_data.setText(time);
        connect_status = (TextView) findViewById(R.id.connect_status);
        glu_image = (ImageView) findViewById(R.id.glu_image);
        upload_button = (Button) findViewById(R.id.upload_button);
        //增加餐前餐后的按钮
        btn_before = (RadioButton) findViewById(R.id.btn_before);
        btn_before.setChecked(true);
        btn_after = (RadioButton) findViewById(R.id.btn_after);
        if (!TextUtils.isEmpty(from) && "jktj".equals(from)) {
            upload_button.setText("确定");
        }
        String type = getIntent().getStringExtra(FLAG_FROM_TYPE);
        if (FLAG_FROM_TYPE_AFTER.equals(type)) {
            btn_after.setChecked(true);
        } else if (FLAG_FROM_TYPE_BEFORE.equals(type)) {
            btn_before.setChecked(true);
        }
        findViewById(R.id.ll_ua).setVisibility(View.GONE);
        findViewById(R.id.ll_chol).setVisibility(View.GONE);
        Button find_device = (Button) findViewById(R.id.find_device);
        find_device.setText("绑定设备");
        find_device.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 选择低功耗蓝牙的名称，然后记录。
                // 点击查找设备后扫描
                scanLeDevice(true);
                showDialog();
            }
        });
        upload_button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                /** 离线保存 */
                try {
                    upload();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void upload() throws Exception {
        String glu = gluse_value_et.getText().toString();
        String gluDate = xt_data.getText().toString();
        if (!TextUtils.isEmpty(from) && "jktj".equals(from)) {
            Intent data = new Intent();
            // glu = 66 + "";
            data.putExtra("glu", glu);
            setResult(6, data);
            finish();
            return;
        } else if (glu.length() > 0) {// 葡萄糖有数据，可以上传
            xuetang uploadBean = new xuetang();
            uploadBean.setIdCard(BaseActivity.getIdCard());
            uploadBean.setTime(gluDate);
            uploadBean.setGlu(glu);
            if (btn_before.isChecked()) {
                uploadBean.setBeforeafter("前");
            } else {
                uploadBean.setBeforeafter("后");
            }
            boolean b = DBService.add(uploadBean);
            if (b) {
                ToastTool.showLong(context, "数据保存成功");
            } else {
                ToastTool.showLong(context, "数据保存失败");
            }
        }
    }

    /*
     * 判断字符串是否包含一些字符 contains
     */
    public static boolean containsString(String src, String dest) {
        boolean flag = false;
        if (src.contains(dest)) {
            flag = true;
        }
        return flag;
    }
}